package com.macauscholar.nfctest

import BaseNfcActivity
import android.content.Intent
import android.nfc.NdefMessage
import android.nfc.NdefRecord
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.Ndef
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import com.macauscholar.pickup.Test.TestKey
import zhiyi.com.teacher_app.RsaKey
import java.nio.charset.StandardCharsets
import java.util.*
import kotlin.experimental.and

/**
 *  package : com.macauscholar.nfctest
 *  author : zhiyi
 *  date : 25/09/2020 11:49 AM
 *  project : NfcTest
 *  description :
 */
class ReadActivity : BaseNfcActivity() {
    private var mNfcText: TextView? = null
    private var mTagText: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_read_text)
        mNfcText = findViewById(R.id.tv_nfctext) as TextView
    }

    override fun onNewIntent(intent: Intent) {
        //1.获取Tag对象
        super.onNewIntent(intent)
        val detectedTag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
        //2.获取Ndef的实例
        val ndef = Ndef.get(detectedTag)
        mTagText = """
             ${ndef.type}
             maxsize:${ndef.maxSize}bytes
             
             
             """.trimIndent()
        readNfcTag(intent)
        mNfcText!!.text = mTagText
    }

    /**
     * 读取NFC标签文本数据
     */
    private fun readNfcTag(intent: Intent) {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent.action) {
            val rawMsgs = intent.getParcelableArrayExtra(
                NfcAdapter.EXTRA_NDEF_MESSAGES
            )
            var msgs: Array<NdefMessage?>? = null
            var contentSize = 0
            if (rawMsgs != null) {
                msgs = arrayOfNulls(rawMsgs.size)
                for (i in rawMsgs.indices) {
                    msgs[i] = rawMsgs[i] as NdefMessage
                    contentSize += msgs[i]!!.toByteArray().size
                }
            }
            try {
                if (msgs != null) {
                    val record = msgs[0]!!.records[0]
                    val textRecord = String(TestKey.decrypt(record.payload,RsaKey.privateKey))
                    mTagText += "$textRecord\n\ntext\n$contentSize bytes"
                }
            } catch (ignored: Exception) {
            }
        }
    }
}